﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WeifenLuo.WinFormsUI.Docking;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

namespace EngineOfEvermore.Editor.AnimationEditor.View
{
    sealed class LayoutManager
    {
        readonly IViewConfig _viewConfig;
        readonly MainForm _mainForm;
        readonly AnimationExplorer _animationExplorer;
        readonly ImageMapView _imageMapView;

        public LayoutManager( IViewConfig viewConfig, MainForm mainform, 
            AnimationExplorer animationExplorer, ImageMapView imageMapView )
        {
            Debug.Assert( mainform != null );
            Debug.Assert( animationExplorer != null );

            _viewConfig = viewConfig;
            _mainForm = mainform;
            _animationExplorer = animationExplorer;
            _imageMapView = imageMapView;
        }

        public void ApplyLayout()
        {
            if ( File.Exists( _viewConfig.ViewLayoutPath ) )
            {
                _mainForm.DockPanel.LoadFromXml( _viewConfig.ViewLayoutPath, _loadLayout );
            }
            else
            {
                _animationExplorer.Show( _mainForm.DockPanel );
                _imageMapView.Show( _mainForm.DockPanel );
            }

            if ( _viewConfig.ViewFormPosition != new Point( -1, -1 ) )
            {
                _mainForm.Location = _viewConfig.ViewFormPosition;
            }

            if ( !_viewConfig.ViewFormSize.IsEmpty )
            {
                _mainForm.Size = _viewConfig.ViewFormSize;
            }

            if ( _viewConfig.ViewIsMaximized )
            {
                _mainForm.WindowState = FormWindowState.Maximized;
            }
            else
            {
                _mainForm.WindowState = FormWindowState.Normal;
            }
        }

        public void SaveLayout()
        {
            _mainForm.DockPanel.SaveAsXml( _viewConfig.ViewLayoutPath, Encoding.UTF8 );

            _viewConfig.ViewFormPosition = _mainForm.Location;
            _viewConfig.ViewFormSize = _mainForm.Size;
            _viewConfig.ViewIsMaximized = _mainForm.WindowState == FormWindowState.Maximized;

            _viewConfig.Save();
        }

        IDockContent _loadLayout( String persistString )
        {
            if ( typeof( AnimationExplorer ).ToString() == persistString )
            {
                return _animationExplorer;
            }
            else if ( typeof( ImageMapView ).ToString() == persistString )
            {
                return _imageMapView;
            }

            return null;
        }
    }
}
